package org.ilc.sample.util;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import org.ilc.Bootstrap;
import org.ilc.sample.Constants;

import java.net.UnknownHostException;

/**
 * @author malb
 */
public class DBUtil {

    private static String mongodbServer;
    private static int mongodbPort;
    private static String dbUser = "root";
    private static String dbPwd = "p@ssw0rd";

    private static Mongo mongo = null;

    static {
        mongodbServer = Bootstrap.getContext ().getAppConfig ().get (Constants.DB_ADDRESS_KEY);
        if (!ValidateUtil.validateStr(mongodbServer))
            throw new RuntimeException ("配置参数："+ Constants.DB_ADDRESS_KEY+" 无效");
//            mongodbServer = Bootstrap.getContext ().getConfig ().get ("server.db.address");
        mongodbPort = Bootstrap.getContext ().getAppConfig ().getInt (Constants.DB_PORT_KEY, 27017);
//            mongodbPort = Integer.parseInt (Bootstrap.getContext ().getConfig ().get ("server.db.port"));

        dbUser = Bootstrap.getContext ().getAppConfig ().get (Constants.DB_USER_KEY);
        dbPwd = Bootstrap.getContext ().getAppConfig ().get (Constants.DB_PASSWD_KEY);

        init ();
    }
    /**
     *
     * @param dbName
     * @return
     */
    public static DB getDB (String dbName) {
        if (mongo == null)
            init ();
        DB db = mongo.getDB(dbName);
        if (!db.isAuthenticated ())
            db.authenticate (dbUser, dbPwd.toCharArray ());
        return db;
    }

    /**
     *
     * @param dbName
     * @param dbCollection
     * @return
     */
    public static DBCollection getDBCollection (String dbName, String dbCollection) {
        if (mongo == null)
            init ();

        DB db = getDB(dbName);

        return db.getCollection(dbCollection);
    }

    private static void init() {
        try {
            mongo = new Mongo(mongodbServer, mongodbPort);
        } catch (UnknownHostException e) {
            throw new RuntimeException("未知服务器地址", e);
        }
    }
}
